<template>
  <div class="container">
    <div class="operationBtn">
      <el-button size="mini" type="primary" @click="addNewRole"
        >新增角色</el-button
      >
      <el-button size="mini" type="danger" @click="deleteRoleHandle"
        >移除角色</el-button
      >
    </div>
    <div class="tableBox">
      <el-table
        border
        :data="routerList"
        v-loading="tableLoading"
        element-loading-text="加载中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column prop="name" label="角色名称"></el-table-column>
        <el-table-column prop="roleStr" label="权限范围"></el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small"
              >修改权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增权限 -->
    <div class="addRoleDialog">
      <el-dialog
        :title="changeType === 'add' ? '新增角色内容' : '修改角色内容'"
        :visible.sync="addRoleVisible"
        @opened="openedDialogHandle"
        @closed="closedDialogHandle"
      >
        <el-form
          label-position="left"
          :model="addFormData"
          ref="addRoleForm"
          :rules="addFormRules"
          label-width="90px"
        >
          <el-form-item label="角色名称:" prop="addRoleName">
            <el-input
              v-model="addFormData.addRoleName"
              placeholder="请输入角色名称"
              style="width:200px"
            />
          </el-form-item>
          <el-form-item label="权限页面:" prop="ids">
            <div class="routerBox">
              <div
                v-for="(item, index) in addRouterList"
                :key="index"
                :class="[checkIdsArr.includes(item.id) ? 'item' : 'item1']"
                @click="checkRouter(item)"
              >
                {{ item.name }}
              </div>
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoleNameHandle('addRoleForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import Const from "@/api/Const.js";
export default {
  name: "roleItem",
  data() {
    return {
      addFormData: {
        addRoleName: "",
        ids: ""
      },
      editId: "",
      changeType: "add",
      tableLoading: false,
      routerList: [],
      addRouterList: [],
      addRoleVisible: false, //新增权限的对话框
      addFormRules: {
        addRoleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        ids: [{ required: true, message: "请选择角色权限", trigger: "change" }]
      },
      checkIdsArr: [],
      checkedTableId: [] //选中table的id
    };
  },
  created() {
    this.initHandle();
  },
  methods: {
    initHandle() {
      this.$axios.get(Const.api.selectRoleListWithMenu).then(res => {
        if (res.data.code == 0) {
          let data = res.data.data;
          if (data.length > 0) {
            this.routerList = data;
            this.routerList.forEach(item => {
              item.roleStr = item.sysRoleMenus
                .map(item => item.menuName)
                .join("、");
            });
          }
        }
      });
    },
    openedDialogHandle() {
      this.getRoleListApiHandle();
    },
    // 关闭弹窗
    closedDialogHandle() {
      this.changeType = "add";
      this.editId = "";
      this.checkIdsArr = [];
      this.addFormData.addRoleName = "";
    },
    getRoleListApiHandle() {
      this.$axios.get(Const.api.selectMenuList).then(res => {
        if (res.data.code == 0) {
          let data = res.data.data;
          this.addRouterList = data;
        }
      });
    },
    addRoleNameHandle(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let requestData = {
            name: this.addFormData.addRoleName,
            menuIdStr: this.checkIdsArr.join(",")
          };
          if (this.editId) {
            requestData.id = this.editId;
          }
          this.$axios
            .get(Const.api.saveRole, {
              params: requestData
            })
            .then(res => {
              let { data } = res;
              if (data.code === 0) {
                 this.$axios.get(Const.api.saveOprateLog,{
                  params:{
                    model:'角色配置',
                    oprate:'添加'
                  }
                });
                this.initHandle();
                this.$message({
                  message: "保存成功！",
                  type: "success"
                });
              } else {
                this.$message.error(data.message);
              }
              this.addRoleVisible = false;
              this.checkIdsArr = [];
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    addNewRole() {
      this.addRoleVisible = true;
    },
    checkRouter({ id }) {
      if (this.checkIdsArr.indexOf(id) === -1) {
        // 不存在 添加
        this.checkIdsArr.push(id);
      } else {
        // 存在 删除
        let index = this.checkIdsArr.findIndex(item => item === id);
        this.checkIdsArr.splice(index, 1);
      }

      if (this.checkIdsArr.length === 0) {
        this.addFormData.ids = "";
      } else {
        this.addFormData.ids = this.checkIdsArr;
      }
    },
    handleSelectionChange(checkedTableId) {
      this.checkedTableId = checkedTableId;
    },
    deleteRoleHandle() {
      if (this.checkedTableId.length === 0) {
        this.$message.error("请先选中需要删除的角色！");
        return false;
      }
      this.$confirm(`确定要删除吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteRoleApiHandle();
        })
        .catch(() => {});
    },
    deleteRoleApiHandle() {
      let ids = this.checkedTableId.map(item => item.id);
      this.$axios
        .get(Const.api.deleteRole, {
          params: {
            id: ids.join()
          }
        })
        .then(res => {
          let { data } = res;
          if (data.code === 0) {
            this.$axios.get(Const.api.saveOprateLog,{
                  params:{
                    model:'角色配置',
                    oprate:'删除'
                  }
                });
            this.initHandle();
            this.$message.success({
              message: "删除成功！",
              type: "success"
            });
          } else {
            this.$message.error(data.message);
          }
        });
    },
    // 修改
    handleClick({ sysRoleMenus, name, id }) {
      this.changeType = "edit";
      let editRoles = sysRoleMenus.map(item => item.menuId);
      this.addFormData.addRoleName = name;
      this.checkIdsArr = editRoles;
      this.addRoleVisible = true;
      this.editId = id;
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  .operationBtn {
    display: flex;
    justify-content: flex-end;
  }
  .tableBox {
    margin-top: 20px;
  }
  .paginationBox {
    margin: 20px;
    display: flex;
    justify-content: flex-end;
  }
  .routerBox {
    display: flex;
    flex-wrap: wrap;
    > div {
      margin: 0 10px;
      padding: 4px 30px;
      border-radius: 10px;
      cursor: pointer;
      &.item1 {
        background-color: #fff;
        color: #333;
        border: 1px solid #999;
      }
      &.item {
        background-color: #78acff;
        color: #fff;
        border: 1px solid #fff;
      }
    }
  }
}
</style>
